<html>
<head>
<script>
var gaia = gaia || {};
gaia.chromeOSLogin = {};

gaia.chromeOSLogin.parent_webview_signin_url_ = 'chrome://chrome-signin';
gaia.chromeOSLogin.parent_webview_oob_url_ = 'chrome://oobe';
gaia.chromeOSLogin.parent_webview_ = undefined;
gaia.chromeOSLogin.parent_webview_url_ = undefined;
gaia.chromeOSLogin.initialized_ = false;
gaia.chromeOSLogin.shouldSendImplicitServices = true;
gaia.chromeOSLogin.shouldSendCloseView = true;

const urlParams = new URLSearchParams(window.location.search);
const useNativeNavigation = !!urlParams.get('use_native_navigation');

function goFirstPage() {
console.error('On first page');
  document.getElementById('page1').hidden = false;
  document.getElementById('page2').hidden = true;
  history.replaceState({}, '', window.location.pathname + '#identifier');
  gaia.chromeOSLogin.backButton(false);
  sendSetPrimaryActionLabel('Next');
  sendSetPrimaryActionEnabled(true);
}

gaia.chromeOSLogin.registerHtml5Listener = function() {
  var onMessage = function(e) {
    if (e.origin == gaia.chromeOSLogin.parent_webview_signin_url_ ||
        e.origin == gaia.chromeOSLogin.parent_webview_oob_url_) {
        gaia.chromeOSLogin.parent_webview_ = e.source;
        gaia.chromeOSLogin.parent_webview_url_ = e.origin;
        if (!gaia.chromeOSLogin.initialized_) {
          gaia.chromeOSLogin.initialized_ = true;
          goFirstPage();
        } else if (e.data == 'primaryActionHit') {
          goNext();
        } else if (e.data == 'secondaryActionHit') {
          sendSetSecondaryActionEnabled(false);
        }
    }
  };
  window.addEventListener('message', onMessage);
  window.addEventListener("popstate", function(e) { goBack(); });
  window.postMessage({
      type: 'gaia_saml_api',
      call: {method: 'initialize', requestedVersion: 1}}, '/');
}

gaia.chromeOSLogin.attemptLogin = function(email, password) {
  var msg = {
    'method': 'attemptLogin',
    'email': email,
  };
  gaia.chromeOSLogin.parent_webview_.postMessage(msg,
      gaia.chromeOSLogin.parent_webview_url_);

  if (!email || !password)
    return;
  // SAML credential passing api for password.
  window.postMessage(
      {type: 'gaia_saml_api',
       call: {method: 'add',
              token: 'token',
              user: email,
              passwordBytes: password,
              keyType: 'KEY_TYPE_PASSWORD_PLAIN'}
      }, '/');
};

gaia.chromeOSLogin.sendUserInfo = function(services) {
  msg = {
    'method': 'userInfo',
    'services': services,
  };
  gaia.chromeOSLogin.parent_webview_.postMessage(msg,
      gaia.chromeOSLogin.parent_webview_url_);
};

gaia.chromeOSLogin.sendCloseView = function() {
  msg = {
    'method': 'closeView',
  };
  gaia.chromeOSLogin.parent_webview_.postMessage(msg,
      gaia.chromeOSLogin.parent_webview_url_);
};

gaia.chromeOSLogin.backButton = function(show) {
  var msg = {
    'method': 'backButton',
    'show': show,
  };
  gaia.chromeOSLogin.parent_webview_.postMessage(msg,
      gaia.chromeOSLogin.parent_webview_url_);
};


function goBack() {
  if (!document.getElementById('page2').hidden) {
    goFirstPage();
  }
}

function goNext() {
  if (!document.getElementById("page1").hidden) {
    document.getElementById("page1").hidden = true;
    document.getElementById("page2").hidden = false;
    history.pushState({}, "", window.location.pathname + "#challengepassword");

    request = new XMLHttpRequest();
    request.open('POST', '/_/embedded/lookup/accountlookup', true);
    request.onreadystatechange = function() {
      if (request.readyState == 4 && request.status == 200) {
        if (request.getResponseHeader("continue"))
          location.assign(request.getResponseHeader("continue"));
      }
    };
    var email = document.getElementById("identifier").value;
    request.send('identifier=' + encodeURIComponent(email));

    gaia.chromeOSLogin.attemptLogin(email, "");
    gaia.chromeOSLogin.backButton(true);
    sendSetPrimaryActionLabel('Next');
    sendSetPrimaryActionEnabled(true);
    sendSetSecondaryActionLabel('Disable button');
    sendSetSecondaryActionEnabled(true);
  } else if (!document.getElementById("page2").hidden) {
    var email = document.getElementById("identifier").value;
    var password = document.getElementById("password").value;
    var services = document.getElementById("services").value;
    if (services) {
      services = JSON.parse(services);
      if (!services)
        services = "Failed to parse test services JSON.";
    } else if (email.endsWith('@corp.example.com') ||
               email.endsWith('@example.test')) {
      // SAML tests.
      services = [];
    } else {
      console.warn("Services are not set for testing.");
      if (gaia.chromeOSLogin.shouldSendImplicitServices)
        services = []
    }

    request = new XMLHttpRequest();
    request.open('POST', '/_/embedded/signin/challenge', true);
    request.onreadystatechange = function() {
      if (request.readyState == 4 && request.status == 200) {
        if (request.getResponseHeader("fake-sync-trusted-vault-keys")) {
          sendSyncTrustedVaultKeys(JSON.parse(
              request.getResponseHeader("fake-sync-trusted-vault-keys")));
        }
        if (services)
          gaia.chromeOSLogin.sendUserInfo(services);
        if (gaia.chromeOSLogin.shouldSendCloseView)
          gaia.chromeOSLogin.sendCloseView();
        history.pushState({}, "", window.location.pathname + "#close");
      }
    };
    request.send('identifier=' + encodeURIComponent(email));

    gaia.chromeOSLogin.attemptLogin(email, password);
  }
}

function onLoad() {
  if (useNativeNavigation) {
    document.getElementById("nextButton").remove();
  }
  gaia.chromeOSLogin.registerHtml5Listener();
}

function sendSetPrimaryActionLabel(label) {
  gaia.chromeOSLogin.parent_webview_.postMessage({
      method: 'setPrimaryActionLabel',
      value: label
    },
    gaia.chromeOSLogin.parent_webview_url_);
}

function sendSetPrimaryActionEnabled(enabled) {
  gaia.chromeOSLogin.parent_webview_.postMessage({
      method: 'setPrimaryActionEnabled',
      value: enabled
    },
    gaia.chromeOSLogin.parent_webview_url_);
}

function sendSetSecondaryActionLabel(label) {
  gaia.chromeOSLogin.parent_webview_.postMessage({
      method: 'setSecondaryActionLabel',
      value: label
    },
    gaia.chromeOSLogin.parent_webview_url_);
}

function sendSetSecondaryActionEnabled(enabled) {
  gaia.chromeOSLogin.parent_webview_.postMessage({
      method: 'setSecondaryActionEnabled',
      value: enabled
    },
    gaia.chromeOSLogin.parent_webview_url_);
}

function sendSetAllActionsEnabled(enabled) {
  gaia.chromeOSLogin.parent_webview_.postMessage({
      method: 'setAllActionsEnabled',
      value: enabled
    },
    gaia.chromeOSLogin.parent_webview_url_);
}

function base64DecodeToArrayBuffer(encoded) {
  // atob() decodes base64 strings into binary string.
  var decoded = atob(encoded);
  var buffer = new ArrayBuffer(decoded.length);
  var view = new Uint8Array(buffer);
  for (var i = 0; i < decoded.length; i++) {
    view[i] = decoded.charCodeAt(i);
  }
  return buffer;
}

// FakeGaia sends the keys in a JSON format that requires some conversion before
// posting to authenticator.js, due to the use of binary blobs in the API.
function convertSyncTrustedVaultKeys(fakeKeys) {
  var keys = {
    obfuscatedGaiaId: fakeKeys.obfuscatedGaiaId,
    encryptionKeys: [
      {keyMaterial: base64DecodeToArrayBuffer(fakeKeys.fakeEncryptionKeyMaterial),
       version: fakeKeys.fakeEncryptionKeyVersion}
    ],
    trustedRecoveryMethods: []
  };
  for (var i = 0; i < fakeKeys.fakeTrustedRecoveryMethods.length; i++) {
    keys.trustedRecoveryMethods.push(
      {publicKey: base64DecodeToArrayBuffer(fakeKeys.fakeTrustedRecoveryMethods[i].publicKey),
       type: fakeKeys.fakeTrustedRecoveryMethods[i].type});
  }
  return keys;
}

function sendSyncTrustedVaultKeys(fakeKeys) {
  gaia.chromeOSLogin.parent_webview_.postMessage({
    method: 'syncTrustedVaultKeys',
    value: convertSyncTrustedVaultKeys(fakeKeys)
  },
  gaia.chromeOSLogin.parent_webview_url_);
}
</script>
</head>
<body onload='onLoad();'>
  Local Auth Server:<br>
  <div id="page1" hidden>
    Email
    <input id="identifier" name="identifier" type="email" spellcheck="false" autocomplete="off" formnovalidate="">
  </div>
  <div id="page2" hidden>
    Password
    <input id="password" name="password" type="password" spellcheck="false" autocomplete="off" formnovalidate="">
    <input id="services" name="services" type="text" spellcheck="false" autocomplete="off" formnovalidate="">
  </div><br>
  <div id='nextButton' onclick='goNext();'>Next</div>
</body>
</html>
